<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" errorPage="error.jsp"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style type="text/css">
h1{
	color:red;
	text-align: center;
	}
}
.kuang{
	margin: auto;
}
.content{
	border: 2px solid red;
	display: flex;
	gap:10px;
	padding: 10px;
}
.column{
	border: 2px solid gray;
	padding: 10px;
	white-space: nowrap;
	flex-grow: 1;
}
a{
	text-decoration: none;
	color:gray;
}
a:hover {
	color:red;
	text-decoration: underline;
}
</style>
<title>分页显示成语</title>
</head>
<body>
<h1>分页显示成语</h1>
<div class='kuang'><%
Class.forName("com.mysql.cj.jdbc.Driver");
String stringPage=request.getParameter("page");
if(stringPage==null)stringPage="1";
int currentPage=Integer.parseInt(stringPage);
int n=8;
int columnCount=14;
int cyCountPerColumn=10;
int pageSize;
int maxPage;
int begin,over;
try(Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/db?allowMultiQueries=true", "root", "12qwas");
	Statement st=cn.createStatement();
	ResultSet rs=st.executeQuery("select count(*) from chengyu");){
	rs.next();
	int total=rs.getInt(1);
	pageSize=columnCount*cyCountPerColumn;
	maxPage=total/pageSize+(total%pageSize==0?0:1);
	if(currentPage<1)currentPage=1;
	else if(currentPage>maxPage)currentPage=maxPage;
	begin=currentPage-n;
	over=currentPage+n;
	if(begin<1){
		over-=begin-1;
		if(over>maxPage)over=maxPage;
		begin=1;
	}else if(over>maxPage){
		begin-=over-maxPage;
		if(begin<1)begin=1;
		over=maxPage;
	}
	
}
%>
	<div class='nav'>
<%
if(begin>1){
	out.println("\t\t<a href='?page=1'>首页</a>");
}
for(int i=begin;i<=over;++i){
	if(i==currentPage){
		out.println("\t\t<b>"+currentPage+"</b>");
	}else{
		out.println("\t\t<a href='?page="+i+"'>"+i+"</a>");
	}
}
if(over<maxPage){
	out.println("\t\t<a href='?page="+maxPage+"'>尾页</a>");
}
%>
	</div>
	<div class='content'>
<%
try(Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/db?allowMultiQueries=true", "root", "12qwas");
	PreparedStatement ps=cn.prepareStatement("select cy from chengyu limit ?,?")){
	ps.setInt(1, (currentPage-1)*pageSize);
	ps.setInt(2, pageSize);
	try(ResultSet rs=ps.executeQuery()){
		for(int i=0;i<columnCount;++i){
			out.println("\t\t<div class='column'>");
			for(int j=0;j<cyCountPerColumn;j++){
				if(rs.next()){
					out.println("\t\t\t<p>"+rs.getString(1)+"</p>");
				}else{
					out.println("\t\t\t<p>    </p>");
				}
			}
			out.println("\t\t</div>");
		}
		
	}
}
%>
</div>
</div>
</body>
</html>